<template>
    <el-dialog v-model="loginStore.isregistedOpen" width="400" :close-on-click-modal="false">
        <div class="login">
            <div class="hader">
                <span>现在!加入我们吧</span>
                <p>注册账号成为我们的成员</p>
            </div>
            <form @submit.prevent="submitForm">
                <input v-model="loginStore.username" type="text" placeholder="用户名" required="true" />
                <input v-model="loginStore.email" type="email" placeholder="邮箱" required="true" />
                <input v-model="loginStore.introduction" type="text" placeholder="签名" required="true" />
                <span style="margin-left: -250px;">头像:</span>
                <el-upload class="avatar-uploader" :action="actionUrl" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
                <input v-model="loginStore.password" type="password" placeholder="密码" required="true" />
                <input v-model="confirmPassword" type="password" placeholder="确认密码" required="true" />
                <input type="button" value="注册" @click="submitForm" />
                <span>已有账号?<a @click="loginStore.isregistedOpen=false" href="#">去登录</a></span>
            </form>
        </div>
    </el-dialog>
</template>

<script setup name="registered">
import { useLoginStore } from '../../../stores/login';
import { ref } from 'vue';
import { ElNotification } from 'element-plus';
import { registered } from '../../../api/login';
import config from '../../../../public/config';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const loginStore = new useLoginStore()
const confirmPassword = ref('');
let actionUrl = config.uploadUrl
let imageUrl = ref('')
let UploadPic = ref('')

const submitForm = async () => {
    if (loginStore.password !== confirmPassword.value) {
        ElNotification({
            title: '注意',
            message: '您输入的两次密码不一致',
            type: 'warning',
            showClose: false,
        });
        return;
    }

    // 邮箱格式验证
    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailPattern.test(loginStore.email)) {
        ElNotification({
            title: '注意',
            message: '您输入的邮箱格式不正确请检查',
            type: 'warning',
            showClose: false,
        });
        return;
    }

    // 使用 registered 函数发送请求
    const params = {
        username: loginStore.username,
        email: loginStore.email,
        password: loginStore.password,
        avatar:UploadPic.value,
        introduction:loginStore.introduction
    };

    try {
        const res = await registered(params)
        if(res.code == 200){
          loginStore.isregistedOpen = false
          ElNotification({
              title: '成功',
              message: res.message,
              type: 'success',
              showClose: false,
          });
          loginStore.username=''
          loginStore.password=''
          loginStore.email=''
          loginStore.introduction = ''
        }else if(res.code == 400){
          ElNotification({
            title: '错误',
            message: res.message,
            type: 'error',
            showClose: false,
        });
        }
    } catch (error) {
        console.error('注册失败:', error);
        ElNotification({
            title: '错误',
            message: '注册失败，请重试。',
            type: 'error',
            showClose: false,
        });
    }
};
//图片上传成功后的方法
function handleAvatarSuccess(response, file, fileList) {
    imageUrl.value = `${config.downloadUrl}?name=${response.data}`
    UploadPic.value = response.data
}
//上传图片之前
function beforeUpload(file) {
    if (file) {
        const suffix = file.name.split('.')[1]
        const size = file.size / 1024 / 1024 < 2
        if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
          ElMessage({
            type: 'info',
            message: '上传图片只支持 png、jpeg、jpg 格式！',
          })
            // this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
            // this.$refs.upload.clearFiles()
            return false
        }
        if (!size) {
          ElMessage({
            type: 'info',
            message: '上传文件大小不能超过 2MB!',
          })
            // this.$message.error('上传文件大小不能超过 2MB!')
            return false
        }
        return file
    }
}
</script>

<style scoped>
.login {
  max-width: 280px;
  background-color: #ffffff;
  border-radius: 5px;
  margin-left: 45px;
}
.hader {
  text-align: center;
  font-size: 22px;
  font-weight: 700;
}
.hader p {
  text-align: center;
  font-size: 18px;
  font-weight: 400;
  color: #706b6b;
}
form {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 20px;
}
form input {
  height: 40px;
  outline: none;
  border: 1px solid #cccccc;
  padding: 10px;
  font-size: 15px;
  border-radius: 8px;
}
form input[type="button"] {
  background-color: rgba(17, 17, 226, 0.562);
  color: #ffffff;
  font-size: 17px;
}
form span {
  text-align: center;
  font-size: 16px;
  padding-top: 10px;
  color: #706b6b;
}
form span a {
  text-decoration: none;
  color: rgba(36, 36, 207, 0.671);
  font-weight: 500;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
